package com.abel.quiz.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @param
 * @author abel.lin
 * @description
 * @date_time 2017/8/4 11:51
 */
public class ApplicationContextHolder implements ApplicationContextAware {

	private static ApplicationContext ctx;

	public void setApplicationContext(ApplicationContext arg)
			throws BeansException {
		this.ctx = arg;
	}
	
	/**
	 * 获取bean对象
	 * @param name
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name){
		return (T) ctx.getBean(name);
	}

	/**
	 * 根据类名获取到bean
	 * @param <T>
	 * @param clazz
	 * @return
	 * @throws BeansException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBeanByName(Class<T> clazz) throws BeansException {
		try {
			char[] cs=clazz.getSimpleName().toCharArray();
			cs[0] += 32;//首字母大写到小写
			return (T) ctx.getBean(String.valueOf(cs));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
